#tasks:
#Remove probes thast have been filtered away from search findings
#Handle quarts window ssytem
#

updateLoadingPlot<- function(PLSmodel,p.value = 0.05,components =NULL,
                             geneLists = NULL,sets = NULL,selSets = NULL,
                             selectedLists = NULL,dev = 1,screenNumber = 1,
                             selectedGenes = NA){
    dev.set(dev)
    screen(n = screenNumber,new = T)
    loading.cols <- as.character(PLSmodel$model$sigLoadings[,1])
    loading.cols[] <- "gray"
    loading.cols[PLSmodel$q < p.value] <- NA
    plot(PLSmodel$model$sigLoadings[,components[1]],
         PLSmodel$model$sigLoadings[,components[2]],col = loading.cols,pch = 20,
         xlab=paste("Component ",as.character(components[1])),
         ylab=paste("Component ",as.character(components[2])),main = "genes",cex = 0.5)
    xy <- xy.coords(x = PLSmodel$model$sigLoadings[PLSmodel$q <= p.value,components[1]],
                    y = PLSmodel$model$sigLoadings[PLSmodel$q <= p.value,components[2]])
    points(xy,col = "red",cex = 0.75,pch = 20)                
    print(selSets)
    if(!is.null(selSets)){
      setInd <- intersect(rownames(PLSmodel$model$sigLoadings),sets[[selSets]])
      setIndSig <- setInd[PLSmodel$q[setInd] <= p.value]
      
      points(PLSmodel$model$sigLoadings[setInd,components[1]],
           PLSmodel$model$sigLoadings[setInd,components[2]],col = "purple",
           pch = 20,cex = 0.5) 
      points(PLSmodel$model$sigLoadings[setIndSig,components[1]],
                  PLSmodel$model$sigLoadings[setIndSig,components[2]],col = "blue",
                  pch = 20,cex = 1) 
    }
    if(length(selectedGenes) > 0){
        if(!is.na(selectedGenes)){
            points(x=PLSmodel$model$sigLoadings[selectedGenes,components[1]],
            y =PLSmodel$model$sigLoadings[selectedGenes,components[2]],col = "purple",pch = 22)   
        }
    }
 abline(h = 0,v = 0)
}


updateSetsPlot<- function(PLSmodel,p.value,sets,selSets = NULL,dev = 1,
                          screenNumber = 3,components = NULL,selectedGenes = NULL){
    dev.set(dev)
    screen(n = screenNumber)
    titleString <- "Sets"
    xlabString <- "component 1"
 
    if(length(selSets) == 1){
        titleString <- paste(selSets,": ",PLSmodel$qSet[selSets])
        print("test")
        print(sets[[selSets]])
        xlabString <- paste("significant:",as.character(sum(PLSmodel$q[sets[[selSets]]] < p.value),
                             na.rm = T),",not significant:",
                             as.character(sum(PLSmodel$q[sets[[selSets]]] > p.value),na.rm =T))
    } 
 
    xy <- xy.coords(x = PLSmodel$Wset[,components[1]],y = PLSmodel$Wset[,components[2]],
                    log = NULL,recycle = FALSE)
    plot(xy,pch = 20,col = "gray",xlab = "",ylab = "",cex = 0.75)
    points(x =PLSmodel$Wset[PLSmodel$qSet < p.value,components[1]],
           y = PLSmodel$Wset[PLSmodel$qSet < p.value,components[2]],col = "red",
           pch = 19,xlab = " ",ylab = " ",cex = 0.75)
    abline(h = 0,v = 0)
    
    print(selSets)
    
    if(!is.null(selSets)){
        points(x =PLSmodel$Wset[selSets,components[1]],y = PLSmodel$Wset[selSets,components[2]],col = "purple",pch = 23,lwd = 2)
    } 

    title(main = titleString, xlab = xlabString)
}

 

updateRawDataPlot <- function(PLSmodel,M,selectedGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList= NULL,sampleLabels = NULL,selectedSample = NULL){

    dev.set(dev)
    screen(n = screenNumber)
    print(PLSmodel$q[selectedGenes])
    #bringToTop()

 
    geneSymbol <- ""
 
    if(!is.null(symbolList)){
        geneSymbol <- symbolList[[selectedGenes]]
    }
   
    if(is.null(timePoints)){
        plot(M[,selectedGenes],main = paste(selectedGenes,"q =", round(PLSmodel$q[selectedGenes],digits = 3),
             geneSymbol),col = sampleColours,pch = 15,ylab = "Expression level")
        text(x=1:dim(M)[1], y =M[,selectedGenes] ,labels = sampleLabels,pos = 4)
    
        if(!is.null(selectedSample)){
            print(selectedSample)
            xy <- xy.coords(x = which(rownames(M) %in% selectedSample),y = M[selectedSample,selectedGenes])
            plot.xy(xy,type = "p",col = "purple",pch = 22,lwd = 2)    
        }
    
    
    }
    else{
        plot(timePoints,M[,selectedGenes],main = paste(selectedGenes,"q = ",round(PLSmodel$q[selectedGenes],
             digits = 3),geneSymbol),pch = 15,col = sampleColours,ylab = "Expression level")
        if(!is.null(selectedSample)){
	    print(selectedSample)
	    xy <- xy.coords(x = timePoints[which(rownames(M) %in% selectedSample)],y = M[selectedSample,selectedGenes])
	    plot.xy(xy,type = "p",col = "purple",pch = 22,lwd = 2)    
	}
    }  
}

updateScoresPlot <- function(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev,selectedSample = NULL){
    dev.set(dev)
    screen(n=2)
    plot(PLSmodel$model$scores[,components[1]],
         PLSmodel$model$scores[,components[2]],xlab=paste("PC:",as.character(components[1]),
         ",",round(PLSmodel$expVarX[components[1]]*100),"% explained"),
         main = "Samples",ylab=paste("PC:",as.character(components[2]),
         ",",round(PLSmodel$expVarX[components[2]]*100),"% explained"),pch = 15,col = sampleColours)
    if(!is.null(sampleLabels)){
        text(PLSmodel$model$scores[,components[1]],PLSmodel$model$scores[,components[2]],labels = sampleLabels,pos = 4)
    }
    else{
        if(!is.null(timePoints)){	
            text(PLSmodel$model$scores[,components[1]],PLSmodel$model$scores[,components[2]],labels = as.character(timePoints),pos = 4)
        }
    }
    
    if(!is.null(selectedSample)){
        xy <- xy.coords(PLSmodel$model$scores[selectedSample,components[1]],y = PLSmodel$model$scores[selectedSample,components[2]])
        plot.xy(xy,type = "p",col = "purple",pch = 22,lwd = 2)    
    }
    
    abline(h = 0,v = 0) 
}




probe2symbol <- function(selectedGene,symbolList =NULL){

    querySymbol <- "Symbol not found" 
    if(is.null(symbolList)){
        print("Background information not loaded")
    } 
    else{
        querySymbol <- symbolList[[selectedGene]]
    }
    return(querySymbol)
}

symbol2probe <- function(querySymbol,symbolList,manualDecide = TRUE){
 
    hitInd <- grep(paste(querySymbol,"+",sep = ""),unlist(symbolList),ignore.case = T)
    print(hitInd)
 
    if(length(hitInd) > 1 & manualDecide){
        print(unlist(symbolList)[hitInd])
        selInd <- menu(names(unlist(symbolList))[hitInd],graphics = T, title = "One of this bunch?")
        print(selInd)
        hitInd <- hitInd[selInd]
        probeID <- names(unlist(symbolList))[hitInd]
    }
 
    if(length(hitInd) > 1 & !manualDecide){
        hitInd <- hitInd[1]
        probeID <- names(unlist(symbolList))[hitInd]
    }
  
    if(length(hitInd)  == 0){
        probeID <- NA
    }
 
    if(length(hitInd)  == 1){
        probeID <- names(unlist(symbolList))[hitInd]
    }
 

    return(probeID)  
}


selectSet <- function(PLSmodel,sets,keyword = NULL){
 
    foundSets <- NULL
    selSets <- NULL
 
    if(is.null(keyword)){
  
        setIDs <- names(sets)  
        setList <- paste(setIDs,PLSmodel$qSet,sep = " q = ")
        iSet <-sort(PLSmodel$qSet,index.return = TRUE)
        selSets <- select.list(setList[iSet$ix],multiple = FALSE,title= "Select gene set")
        selSets <- unlist(strsplit(selSets," q = ",fixed = T))[1]
  
   
        if(is.na(selSets)){
        #Try without sorting on q values
            selSets <- select.list(setIDs,title= "Select gene set",multiple = T)
        }
 
        if(length(selSets)==0){
        #Try a search
        print("Enter gene set search term")
        keyword <- readLines(n = 1)
        } 
     }
 
     if(!is.null(keyword)){
         foundSets <- grep(paste(keyword,"+",sep = ""),names(sets),ignore.case = T)
         if(length(foundSets > 0.5)){
         foundSets <- names(sets)[foundSets]
         selSets <- select.list(foundSets,multiple = FALSE, title = "Any of this bunch?")
     }
     else{
         print("search term not found")
     }  
 }
 return(selSets)
}





miirPLSplot <- function(PLSmodel,M = NULL,components= c(1,2),p.value = 0.05,
                    timePoints = NULL,search_option = "symbol",
                    sampleLabels = NULL,sampleColours = "black",symbolList = NULL,
                    geneLists = NULL,sampleLists = list()){
    
    #search_option = c("symbol","clone","affy")
    ##Issues Set report after selection of set
    ##Inlude fisher p values
    ##Download selected litterature
    ##Publish set method
    ##Integrate with arnars Graph methods
    ##Integrate with Martin Ks graph system
    colourMatrix <-NULL
    
    if(is.null(geneLists) | !any("significantGenes" %in% names(geneLists))){
        geneLists <- c(geneLists,list(significantGenes = names(PLSmodel$q)[PLSmodel$q < p.value]))
    }
    
    if(is.null(M)){
        M <- PLSmodel$X
    }
    
    if(is.matrix(sampleColours)){
        colourMatrix <- sampleColours
        sampleColours <- colourMatrix[,1]
    }
    
    library(annotate)
    library(geneplotter)
    library(gstat)
    library(MASS)
    #initialize the four plots
    viewGenes <- colnames(M)[1]
    selectedGenes <- NULL
    selectedSets <- NULL
    selectedLists <- NULL
    restrictClicks <- FALSE
    selectedSample <- NULL
    prevSelectedGenes <- NULL
    
    chrClassObject <- NULL
    pubmedData <- NULL
    sets <- PLSmodel$sets


    #source("c:/MiiR/plsPlotCoreFunctions.r")
    #loading plot
    if(.Platform$GUI == "Rgui"){
        x11()
    }
    if(.Platform$GUI == "quartz"){
        quartz()
    }
    
    
    par(bg = "white",cex.main = 0.75)
    split.screen(figs = c(2,2), erase = TRUE)
    mainPlot <- dev.cur()
 
    screen(n=2)
    
    updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot)

    updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes)
    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList)
    if(!is.null(sets)){
        updateSetsPlot(PLSmodel,p.value,components = components,sets = sets,dev = mainPlot,screenNumber = 3)
    }
    if(!is.null(chrClassObject)){
        #x11()
        chrPlot <- dev.cur()
        updateChrPlot(chrClassObject,selectedGenes,dev = chrPlot,new.plot = TRUE)
    } 

    if(!is.null(pubmedData)){
        #x11()
        pubmedPlot <- dev.cur()
        updatePubmedPlot(W= PLSmodel$W,Wpaper=pubmedData$Wpapers,dev=pubmedPlot,components = components,selectedGenes = NULL)
    }

    new.cycle <- TRUE

    while (new.cycle == TRUE){
        availableOptions <- c("gene","annotate gene","set map","samples","raw data","gene selections","export",
                              "sample selection","clicks","find","quit","multiple sets")
        type <-  menu(availableOptions,title = "Choose action",graphics = FALSE)
        type <- availableOptions[type]
        
        if(type == "gene selections"){
            selectionOptions <- c("multiple genes","unselect all","unselect","remove insignificant genes",
                                   "select genes in geneList","select genes in selected sets","multiple samples",
                                   "add selected to geneList","intersect selected genes and geneList","back")
            type <- menu(selectionOptions,title = "Choose gene selection action",graphics = FALSE)
            type <- selectionOptions[type] 
        }
        
        if(type == "sample selection"){
            selectionOptions <- c("select multiple samples","clear sample selection","change sample colour scheme",
                                  "add selected to sampleList","select samples in sampleList","back")
            type <- menu(selectionOptions,title = "Choose action on sample(s)",graphics = FALSE)
            type <- selectionOptions[type] 
        }
        
        if(type == "export"){
            selectionOptions <- c("export geneList","export sets result","prepare pathway map","back")
            type <- menu(selectionOptions,title = "Choose what to export",graphics = FALSE)
            type <- selectionOptions[type] 
        }
        
        if(type == "find"){
            selectionOptions <- c("find probe","find symbol","find sample","sets list","back")
	    type <- menu(selectionOptions,title = "Choose what to find",graphics = FALSE)
            type <- selectionOptions[type] 
	}
        
        new.task <- FALSE
        
        if(type == "back"){
            new.task = TRUE        
        }
 
        while (new.task == FALSE & new.cycle == TRUE){
 
            if (type == "gene"){
  
                dev.set(mainPlot)
                screen(n = 1,new = F)
    
                if(!restrictClicks|length(selectedGenes) == 0 & length(selectedSets) == 0){
                    ind <- identify(PLSmodel$model$sigLoadings[,components[1]],PLSmodel$model$sigLoadings[,components[2]],plot = F,n=1)
                }
                else{    
                    ind <- identify(PLSmodel$model$sigLoadings[selectedGenes,components[1]],PLSmodel$model$sigLoadings[selectedGenes,components[2]],plot = F,n  =1)
                    ind <- which(colnames(M) == selectedGenes[ind])
                } 
    
                if (length(ind) > 0.5){
                    viewGenes <- colnames(M)[ind]
                    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)      
                }
                else{
                    new.task <- TRUE
                }
            }

  
            if (type == "annotate gene"){
  
                dev.set(mainPlot)
                screen(n = 1,new = F)
 
                if(!restrictClicks|length(selectedGenes) == 0){
                    ind <- identify(PLSmodel$model$sigLoadings[,components[1]],PLSmodel$model$sigLoadings[,components[2]],plot = F,n  =1)
                }
                else{
                    ind <- identify(PLSmodel$model$sigLoadings[selectedGenes,components[1]],PLSmodel$model$sigLoadings[selectedGenes,components[2]],plot = F,n  =1)
                    ind <- which(colnames(M) == selectedGenes[ind])
                }
    
                if (length(ind) > 0.5 & search_option != "symbol"){
                    viewGenes <- colnames(M)[ind]
                    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList)      
                    egonURL <- paste("http://www.genetools.microarray.ntnu.no/adb/singlesearch.php?action=singlesearch&title=",search_option,"&criteria=",sep = "")
                    geneURL <- paste(egonURL,viewGenes,sep = "")
                    print(egonURL)
                    print(geneURL)
                    browseURL(url=geneURL,browser = NULL)
                }
                if (length(ind) > 0.5 & search_option == "symbol"){
		    viewGenes <- colnames(M)[ind]
		    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList)      
		    egonURL <- paste("http://www.genetools.microarray.ntnu.no/adb/singlesearch.php?action=singlesearch&title=",search_option,"&criteria=",sep = "")
		    geneURL <- paste(egonURL,symbolList[[viewGenes]],sep = "")
		    print(egonURL)
		    print(geneURL)
		    browseURL(url=geneURL,browser = NULL)
                }
                if(length(ind) == 0){
                    new.task <- TRUE
                    updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets) 
                }
            }

            if(type == "unselect"){
                dev.set(mainPlot)
                screen(n = 1,new = F)
                if(length(selectedGenes) > 0){
                    ind <- identify(PLSmodel$model$sigLoadings[selectedGenes,components[1]],PLSmodel$model$sigLoadings[selectedGenes,components[2]],plot = F,n  =1)
                    if(!length(ind) == 0){
                        selectedGenes <- selectedGenes[-ind]
                        updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets)
                    }
                    else{
                        new.task = TRUE
                    }
                }
                else{
                    new.task = TRUE
                }
            }   


            if (type == "multiple genes"){
                dev.set(mainPlot)
                screen(n = 1,new = F)
                loc <- locator(n = 9,type = "l")
                pip <- point.in.polygon(point.x = PLSmodel$model$sigLoadings[,components[1]], point.y = PLSmodel$model$sigLoadings[,components[2]], pol.x = loc$x, pol.y = loc$y)
                print(as.data.frame(PLSmodel$q[pip != 0]))
                selectedGenes <- unique(c(selectedGenes,colnames(M)[pip != 0]))
                points(x=PLSmodel$model$sigLoadings[colnames(M)[pip != 0],components[1]],y =PLSmodel$model$sigLoadings[colnames(M)[pip != 0],components[2]],col = "purple",pch = 22)
                updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets)
   
                new.task = TRUE  
            } 

            if (type == "find probe"){
                dev.set(mainPlot)
                #bringToTop()
                screen(n = 1,new =F)
  
                #Ask for ID
                selectedGene <- readLines(n = 1)
                if(any(selectedGene == colnames(M))){
                    dev.set(mainPlot)
                    screen(n = 1,new = F)
                    points(x=PLSmodel$model$sigLoadings[selectedGene,components[1]],y =PLSmodel$model$sigLoadings[selectedGene,components[2]],col = "purple",pch = 22)
                    selectedGenes <- unique(c(selectedGenes,selectedGene))
                    updateRawDataPlot(PLSmodel,M,selectedGene,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints)      
                }
                else{
                    print("probeID not found")
                    new.task = T
                }
            }

            if (type == "find symbol"){
                dev.set(mainPlot)
                #bringToTop()
                screen(n = 1,new =F)
   
                #Ask for ID
                querySymbol <- readLines(n = 1)
                if(is.null(symbolList)){
                    print("Background information not loaded")
                    new.task = T 
                }  
                else{
                    selectedGene <- symbol2probe(querySymbol,symbolList)
                    print(selectedGene)
     
                    if(!is.na(selectedGene)){
                        if (any(selectedGene == colnames(M))){
                            dev.set(mainPlot)
                            screen(n = 1,new = F)
                            points(x=PLSmodel$model$sigLoadings[selectedGene,components[1]],y =PLSmodel$model$sigLoadings[selectedGene,components[2]],col = "purple",pch = 22)
                            updateRawDataPlot(PLSmodel,M,selectedGene,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList)
                            selectedGenes <- unique(c(selectedGene,selectedGenes))
                        }
                    } 
    
                    if(length(selectedGene) < 1 | is.na(selectedGene)){
                        print("Gene symbol not found")
                        new.task = T      
                    }
                    else{
                        selectedGenes <- c(selectedGenes,selectedGene)
                    } 
                }
            } 

            if (type == "sets list"){
                selectedSets <- selectSet(PLSmodel,sets,keyword = NULL)
                if(length(selectedSets) == 0){
                    selectedSets <- NULL
                }
 
                updateSetsPlot(PLSmodel,p.value,components = components,sets = sets,selSets = selectedSets,dev = mainPlot,screenNumber = 3)
                new.task = T
                updateLoadingPlot(PLSmodel,p.value,components = components,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)

            } 
            
            if( type == "set map"){
                dev.set(mainPlot)
                screen(n = 3,new = F)
                #bringToTop()
                ind <- NULL
                ind <- identify(PLSmodel$Wset[,components[1]],PLSmodel$Wset[,components[2]],n = 1,labels = names(sets))
 
                if(length(ind)>0){
                    selectedSets <- names(sets)[ind]
                    
                    if(restrictClicks & (length(selectedGenes) == 0 | length(selectedGenes) == length(prevSelectedGenes))){
		        selectedGenes <- sets[[selectedSets]]
		        prevSelectedGenes <- selectedGenes
                    }
                    
                    updateSetsPlot(PLSmodel,p.value,components = components,sets = sets,selSets = selectedSets,dev = mainPlot,screenNumber = 3)
                    updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
                }
                else{
                    new.task <- T
                } 
            }


            if (type == "multiple sets"){
                dev.set(mainPlot)
                screen(n = 3,new = F)
                loc <- locator(n = 9,type = "l")
                pip <- point.in.polygon(point.x = PLSmodel$Wset[,components[1]], point.y = PLSmodel$Wset[,components[2]], pol.x = loc$x, pol.y = loc$y)
                #print(as.data.frame(PLSmodel$qSet[pip != 0]))
                selectedSets <- unique(c(selectedSets,names(PLSmodel$sets)[pip != 0]))
                #points(x=PLSmodel$Wset[colnames(M)[pip != 0],components[1]],y =PLSmodel$Wset[colnames(M)[pip != 0],components[2]],col = "purple",pch = 22)
                #updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets)
   
                sigSets <- selectedSets[PLSmodel$qSet[selectedSets] < p.value]  
                setReport <- matrix(0,nrow = length(sigSets),ncol = 3)
                rownames(setReport) <- sigSets
                colnames(setReport) <- c("significant","notSigificant","qSet")
    
                for (sigSet in sigSets){
                    setReport[sigSet,1] <- sum(PLSmodel$q[sets[[sigSet]]] <= p.value)
                    setReport[sigSet,2] <- sum(PLSmodel$q[sets[[sigSet]]] > p.value)
                    setReport[sigSet,3] <- PLSmodel$qSet[sigSet]
                } 
                
                setInd <- sort(setReport[,1]/setReport[,2],decreasing = TRUE,index.return = T)
                setReport <- setReport[setInd$ix,]
                
                write.table(setReport,sep = "\t",quote = F, file = "selectedSetsReport.txt")
                print("significnat selected sets written to selectedSetsReport.txt")
                print("significant sets in selected area :")
                print(setReport)
                selectedSets <- NULL
                new.task = TRUE  
            }


            if(type == "unselect all"){
                selectedGenes <- NULL
                selectedSets <- NULL
                
                updateLoadingPlot(PLSmodel,p.value,components = components,geneLists = NULL,dev = mainPlot,screenNumber = 1,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets)
                
                if(!is.null(sets)){
                    updateSetsPlot(PLSmodel,p.value,components = components,sets = sets,dev = mainPlot,screenNumber = 3)
                }
 
                new.task <-T
            }

            if (type == "clicks"){
                restrictClicks <- !restrictClicks
                print(paste("only selected genes can be clicked: ",as.character(restrictClicks)))
                
                if(length(selectedGenes) == length(prevSelectedGenes)){
                    selectedGenes <- NULL
                    prevSelectedGenes <- NULL
                }
                if(length(selectedGenes == 0) & restrictClicks & !is.null(selectedSets)){
                    selectedGenes <- sets[[selectedSets]]
                }
                new.task <- T
            }


            if (type == "remove insignificant genes"){
                selectedGenes <- selectedGenes[PLSmodel$q[selectedGenes] < p.value]
                print(paste("only selected genes can be clicked: ",as.character(restrictClicks)))
                updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
                new.task <- T
            }

            if( type == "select genes in selected sets"){
                if(!is.null(selectedSets)){
                    selectedGenes <- unique(c(selectedGenes,sets[[selectedSets]]))
                } 
                new.task = T
            }

            if(type == "select genes in geneList"){
                if (!is.null(geneLists)){
                    selList <- select.list(names(geneLists),multiple = TRUE,title= "Select geneList")
                    selectedGenes <- unique(c(selectedGenes,geneLists[[selList]]))
                    updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
                } 
                new.task = T
            }

            if(type == "intersect selected genes and geneList"){
	        if (!is.null(geneLists)){
	            selList <- select.list(names(geneLists),multiple = TRUE,title= "Select geneList")
	            selectedGenes <- intersect(selectedGenes,geneLists[[selList]])
	            updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
	        } 
	    new.task = T
            }



            if(type == "export geneList"){
                if (!is.null(geneLists)){
                    selList <- select.list(names(geneLists),multiple = FALSE,title= "Select geneList")
                    selectedGenes <- unique(c(geneLists[[selList]]))
  
                    if(is.null(timePoints)){ 
                        exportData <-as.data.frame(list(probe = selectedGenes,sym =  unlist(symbolList)[selectedGenes], M = t(M[,selectedGenes]),qValue = PLSmodel$q[selectedGenes]))
                    }
                    else{
                        Mexport <- matrix(0,nrow = length(selectedGenes),ncol = length(unique(timePoints)))
                        rownames(Mexport) <- selectedGenes
                        colnames(Mexport) <- unique(timePoints)
   
                        for(sg in selectedGenes){
                            for (ts in unique(timePoints)){  
                                Mexport[sg,as.character(ts)] <- mean(M[timePoints == ts,sg])
                            }
                        }
                        exportData <-as.data.frame(list(probe = selectedGenes,sym =  unlist(symbolList)[selectedGenes], M = Mexport,qValue = PLSmodel$q[selectedGenes]))
                    }
  
                    write.table(exportData,file = paste(selList,".txt"),sep = "\t",quote = F)
  
                    updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
                } 
            new.task = T
            }

            if( type =="add selected to geneList"){
                if(length(selectedGenes) > 0){
                    print("enter name for new geneList")
                    newListName <- readLines(n = 1)
                    geneLists[[newListName]] <- selectedGenes
                }
            new.task = T
            }

            if(type =="export sets result"){ 
                sigSets <- names(PLSmodel$qSet)[PLSmodel$qSet < p.value]
                setReport <- matrix(0,nrow = length(sigSets),ncol = 3)
                rownames(setReport) <- sigSets
                colnames(setReport) <- c("significant","notSigificant","qSet")
 
                for (sigSet in sigSets){
                    setReport[sigSet,1] <- sum(PLSmodel$q[sets[[sigSet]]] <= p.value)
                    setReport[sigSet,2] <- sum(PLSmodel$q[sets[[sigSet]]] > p.value)
                    setReport[sigSet,3] <- PLSmodel$qSet[sigSet]
                } 
 
                write.table(setReport,sep = "\t",quote = F, file = "setReport.txt")

                new.task = T
            }
            
            
            if (type == "samples"){
	      
	        dev.set(mainPlot)
	        screen(n = 2,new = F)
	        selectedSample <- rownames(M)[identify(x = PLSmodel$model$scores[,components[1]],y = PLSmodel$model$scores[,components[2]],n = 1,plot = F)]
	        print(selectedSample)
	        updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)                  
	        
	        if(length(selectedSample) > 0){
	            new.task <- FALSE
	        }
	        else{
	            new.task <- TRUE
	        }
            }
            
            if (type == "raw data"){
	    	      
	    	dev.set(mainPlot)
	    	screen(n = 4,new = F)
	    	
	    	if(!is.null(timePoints)){
	    	    print("test0")
	    	    print(viewGenes)
	    	    selectedSample <- rownames(M)[identify(x = timePoints,y = M[,viewGenes[1]],plot = F,n = 1)]
	    	    print(selectedSample)
	    	}
	    	
	    	if(is.null(timePoints)){
	    	    selectedSample <- rownames(M)[identify(x = 1:dim(M)[1],y = M[,viewGenes[1]],plot = F,n = 1)]
		    print(selectedSample)
	    	}
	        
	        
	        
	        if(length(selectedSample) > 0){
	            updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot,selectedSample = selectedSample)
                    new.task <- FALSE 
	    	}
	    	else{
	            new.task <- TRUE 
                }
            }
            
            if(type == "select multiple samples"){
                dev.set(mainPlot)
                screen(n = 2,new = F)

                loc <- locator(n = 9,type = "l")
	        pip <- point.in.polygon(point.x = PLSmodel$model$scores[,components[1]], point.y = PLSmodel$model$scores[,components[2]], pol.x = loc$x, pol.y = loc$y)
	        print(rownames(PLSmodel$model$scores)[pip != 0])
	        selectedSample <- unique(c(selectedSample,rownames(PLSmodel$model$scores)[pip != 0]))
                updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)     
                updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot,selectedSample = selectedSample)    

                new.task <- TRUE
            
            }
            
            if(type == "clear sample selection"){
                selectedSample <- NULL
                updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot,selectedSample = selectedSample)    
                updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)     
            
                new.task <- T
            
            }   
            
            if(type == "add selected to sampleList"){
                if(length(selectedSample) > 0){
                    print("enter name for new sampleList")
                    newListName <- readLines(n = 1)
                    sampleLists[[newListName]] <- selectedSample
                }
                new.task <- T
            }

            if(type == "select samples in sampleList"){
                if (!is.null(geneLists)){
                    selSampleList <- select.list(names(sampleLists),multiple = FALSE,title= "Select sampleList")
	            selectedSample <- unique(c(selectedSample,sampleLists[[selSampleList]]))
	            updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot,selectedSample = selectedSample)    
		    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)     
	            
	        } 
	        new.task = T
	    }
	    


            
            if(type == "prepare pathway map"){
	      #select pathway from list and plot pathway
	        setIDs <- names(sets)
	        updateLoadingPlot(PLSmodel,p.value,components = components,selectedGenes = selectedGenes,sets = sets,selSets = selectedSets,geneLists = NULL,dev = mainPlot,screenNumber = 1)
	    
	        setList <- paste(setIDs,PLSmodel$qSet,sep = " q = ")
	        iSet <-sort(PLSmodel$qSet,index.return = TRUE)
	        selSets <- select.list(setList[iSet$ix],multiple = TRUE,title= "Select gene set")
	        selSets <- unlist(strsplit(selSets," q = ",fixed = T))[1] #problem with multiple selectd?
	        print(selSets)
	        
	        if(is.na(selSets)){
	         #Try without sorting on q values
	         selSets <- select.list(setIDs,multiple = FALSE,title= "Select gene set")
	        }
	      	  
	        loading.cols <- as.character(PLSmodel$model$sigLoadings[,1])
	        loading.cols[] <- NA
	        names(loading.cols) <- rownames(PLSmodel$model$sigLoadings)
	        loading.cols[PLSmodel$q < p.value] <- NA
	        #print(loading.cols)
	        loading.cols[sets[[selSets]]] <- "green"
	            
	        # Compute loading density
	        dev.set(mainPlot)
	        #bringToTop()
	        screen(n = 1,new = F)
	        
	        title(main =paste(selSets," q = ", as.character(round(PLSmodel$qSet[selSets],2))),xlab = paste("significant:",as.character(sum(loading.cols == "red",na.rm = T)),",not significant:",as.character(sum(loading.cols=="green",na.rm =T))))
	     
	        #do PCA of pathway data
	        localPCA <- prcomp(PLSmodel$model$sigLoadings[sets[[selSets]],components],center = FALSE)
	        print(PLSmodel$model$sigLoadings[(sets[[selSets]]),components])
	        abline(a = 0, b = localPCA$rotation[2]/localPCA$rotation[1],lty = "dashed")
	        set.cols <- as.character(PLSmodel$model$sigLoadings[sets[[selSets]],1])
	        set.cols[] <- "NA"
	        #set.cols[localPCA$x[,1] > 0 & PLSmodel$q[sets[[selSets]]] < 2*p.value] <- "cyan"
	        set.cols[localPCA$x[,1] > 0 & PLSmodel$q[sets[[selSets]]] < p.value] <- "yellow"
	        #set.cols[localPCA$x[,1] < 0 & PLSmodel$q[sets[[selSets]]] < 2*p.value] <- "yellow"
	        set.cols[localPCA$x[,1] < 0 & PLSmodel$q[sets[[selSets]]] < p.value] <- "blue"
	        xy <- xy.coords(x = PLSmodel$model$sigLoadings[sets[[selSets]],components[1]],y = PLSmodel$model$sigLoadings[sets[[selSets]],components[2]])
	        points(xy,type ="p", col = set.cols,pch = 23,lwd = 2)
	        pcaSign <- as.character(sign(localPCA$x[,1]))
	        pcaSign[pcaSign == "1"] <- "+"
	        pcaSign[pcaSign == "-1"] <- "-"
	        pwtxt <- as.data.frame(list(genes = unlist(symbolList)[sets[[selSets]]],q = PLSmodel$q[sets[[selSets]]],s = pcaSign),row.names = as.character(1:length(sets[[selSets]])))
	        pwtxt <- pwtxt[!is.na(set.cols),]
	        write.table(pwtxt,file = paste(selSets,".txt"),row.names = F,col.names = F,sep = "\t",quote = FALSE)
	        
	      
	        print(getwd())
	        new.task = T
	        
            }
            
            
	    if(type == "change sample colour scheme"){
	        
	        if(!is.null(colourMatrix)){
	            selScheme <- select.list(colnames(colourMatrix),multiple = FALSE,title= "Select gene set")
	            print(selScheme)
	            sampleColours <- colourMatrix[,selScheme]
	            updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot)
	        }    
	        else{
	           print("only one colour scheme loaded")
	        }   
	        
	        new.task <- T
            }
            
            if(type == "find sample"){
                print("Enter sample query")
                querySymbol <- readLines(n = 1)
                sampleCandidates <- grep(paste(querySymbol,"+",sep = ""),rownames(PLSmodel$model$scores),
                                         ignore.case = T)
                
                if(length(sampleCandidates) > 1){
		    selInd <- menu(rownames(PLSmodel$model$scores)[sampleCandidates],graphics = T, title = "One of this bunch?")
		    hitInd <- sampleCandidates[selInd]
		    selectedSample <- unique(c(selectedSample,rownames(PLSmodel$model$scores)[hitInd]))
		}
		
		if(length(sampleCandidates) == 1){
		    selectedSample <- unique(c(rownames(PLSmodel$model$scores)[sampleCandidates],selectedSample))		
		}
                
                if(length(sampleCandidates) == 0){
                    print("nothing found")
                    new.task <- T
                }
                else{
                    updateScoresPlot(PLSmodel,sampleColours,sampleLabels,components,timePoints,dev = mainPlot,selectedSample = selectedSample)    
                    updateRawDataPlot(PLSmodel,M,viewGenes,sampleColours,dev = mainPlot,screenNumber = 4,timePoints = timePoints,symbolList = symbolList,selectedSample = selectedSample)     
	        }    
                
              
            }

            if (type == "quit"){
                new.cycle <- F
                new.task <- T
            } 
         }
     }
Lists <- list(geneLists = geneLists,sampleLists = sampleLists)    
return(Lists)
}